package com.cs.client;

import com.cs.entity.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.Callable;

import static com.cs.client.ClientBootStrap.curator;

    public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private Object result;
    private RpcRequest para;
    private String path;//连接服务器在zookeeper上的节点路径
    private String value;//连接服务器的ip:port

    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */

    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = msg.toString();
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */

    public synchronized Object call() throws Exception {
        long startTime = System.currentTimeMillis();
        context.writeAndFlush(para);
        wait();
        long finshTime = System.currentTimeMillis();
        long time = finshTime-startTime;//读取数据消耗时间
        System.out.println("读取数据消耗时间："+time);
        curator.setData().forPath(path,(value + "," + time).getBytes());
        context.close();//获得数据,关闭当前连接
        return result;
    }

    /**
     设置参数
     */
    void setPara(RpcRequest rpcRequest,String path,String value) {
        this.para = rpcRequest;
        this.path = path;
        this.value = value;
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }

    //超时处理
    public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.err.println("请求超时了");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String type = "";
            if (event.state() == IdleState.READER_IDLE) {
                type = "read idle";
                System.err.println("读取超时，直接删除连接超时的节点:::"+path);
                curator.delete().deletingChildrenIfNeeded().forPath(path);

            } else if (event.state() == IdleState.WRITER_IDLE) {
                type = "write idle";
            } else if (event.state() == IdleState.ALL_IDLE) {
                type = "all idle";
            }
            System.err.println(ctx.channel().remoteAddress()+"超时类型：" + type);
        } else {
            super.userEventTriggered(ctx, evt);
        }
        //关闭连接
        ctx.close();

    }
}
